#include <iostream>
#include <queue>
#include <vector>

using namespace std;


struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


/**
 * @brief The width of binary trees grows exponentially with respect to height!
 *        Need to use unsigned long long!!!
 */
class Solution {
public:
    // 这是我的[习惯]做法
    int widthOfBinaryTree(TreeNode* root) {
        if (!root) return 0;
        
        using long_int = unsigned long long;
        queue<pair<TreeNode*, long_int>> q; q.push({root, 1L});
        long_int max_width = 1;
        while (!q.empty()) {
            long_int level_width = q.size();  // 注意过程变量一定要用 long_int!
            long_int l, r;
            for (int i=0; i<level_width; i++) {
                auto [node, index] = q.front(); q.pop();
                if (node->left) q.push({node->left, index*2});
                if (node->right) q.push({node->right, index*2+1});
                if (i==0) l = index;
                if (i==level_width-1) r = index;
            }

            max_width = max(max_width, (long_int)(r-l+1));
        }

        return max_width;
    }


    int widthOfBinaryTree2(TreeNode* root) {
        if (!root) return 0;
        
        using long_int = unsigned long long;
        long_int max_width = 1;
        vector<pair<TreeNode*, long_int>> q; q.emplace_back(root, 1L);
        while (!q.empty()) {
            int level_width = q.size();
            vector<pair<TreeNode*, long_int>> temp;
            
            for (auto& [node, index] : q) {
                if (node->left) temp.emplace_back(node->left, index*2);
                if (node->right) temp.emplace_back(node->right, index*2+1);
            }
            max_width = max(max_width, q.back().second - q[0].second + 1);
            q = move(temp);
        }

        return max_width;
    }
};
